const fs = require('fs');
const echartsScript = fs.readFileSync(process.argv[3], 'utf8');
const nodeHtmlToImage = require('node-html-to-image');

// 从命令行参数获取输出路径
const outputPath = process.argv[2];

// 从标准输入
let inputData = '';
process.stdin.on('data', chunk => {
    inputData += chunk;
});

process.stdin.on('end', () => {
    try {
        const option = inputData;

        const html = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <script>${echartsScript}</script>
    </head>
    <body>
        <div id="chart" style="width: 600px; height: 400px;"></div>
        <script>
            const chart = echarts.init(document.getElementById('chart'));
            const option = ${option};
            chart.setOption(option);
        </script>
    </body>
    </html>
    `;

        nodeHtmlToImage({
            output: outputPath,
            html: html,
            timeout: 5000
        }).then(() => {
            console.log('成功，图片已生成: ' + outputPath);
            process.exit(1);
        }).catch(err => {
            console.error('失败,原因:', err);
            process.exit(2);
        });

    } catch (e) {
        console.error('失败,解析配置失败:', e.message);
        process.exit(2);
    }
});